package cn.hxzy.controller;

import cn.hxzy.domain.ExamEvaluation;
import cn.hxzy.domain.Task;
import cn.hxzy.domain.TaskManager;
import cn.hxzy.domain.vo.SelectCourseAndStudy;
import cn.hxzy.domain.vo.TaskSave;
import cn.hxzy.domain.vo.TaskVo;
import cn.hxzy.response.R;
import cn.hxzy.response.StatusEnum;
import cn.hxzy.service.ExamEvaluationService;
import cn.hxzy.service.StudentService;
import cn.hxzy.service.TaskManagerService;
import cn.hxzy.service.TaskService;
import cn.hxzy.util.AliOssUtil;
import com.aliyun.oss.common.utils.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private ExamEvaluationService examEvaluationService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private TaskManagerService taskManagerService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    /**
     * 查询习题列表
     *
     * @param stuId 学员id
     * @return 习题列表
     */
    @GetMapping("/selectList/{StudentId}")
    public R<List<ExamEvaluation>> getList(@PathVariable("stuId") int stuId) {
        List list = examEvaluationService.getList(stuId);
        return R.success(list);
    }

    /**
     * 模糊查询
     *
     * @param practiceName 习题名称
     * @return 习题对象
     */
    @GetMapping("/select")
    public R<List<ExamEvaluation>> selectId(String practiceName) {
        List<ExamEvaluation> examEvaluations = examEvaluationService.selectListByName(practiceName);
        return R.success(examEvaluations);
    }

    /**
     * 提交作业
     *
     * @param taskManager 作业详细信息实体类
     * @return
     */
    @PostMapping("/uptask")
    public R uptask(@RequestBody TaskManager taskManager) {
        //String userId = ThreadLocalUtil.getUser().getUserId().toString();
        //获取提交次数
        Integer count = studentService.count(1, taskManager.getTaskId());
        taskManager.setStudentId(1);
        //提交时间
        taskManager.setSubmitTime(LocalDateTime.now());
        boolean b = false;
        //判断是否是第一次提交
        if (count == null) {
            //提交次数
            taskManager.setSubmitCount(1);
            //提交作业
            b = taskManagerService.save(taskManager);
        } else {
            //提交次数
            taskManager.setSubmitCount(count + 1);
            //修改作业
            b = taskManagerService.updateTaskManger(taskManager);
        }
        if (b) {
            return R.success(b);
        }
        return R.error(StatusEnum.PARAM_INVALID);
    }


    /**
     * 查询当前当个作业详情
     *
     * @param taskId 作业id
     * @return
     * @throws Exception
     */
    @GetMapping("/selectTaskManager/{taskId}")
    public R<TaskVo> selectTaskManager(@PathVariable("taskId") Integer taskId) {
        TaskVo taskVo = taskService.selectTaskVo(taskId);
        if (taskVo != null) {
            return R.success(taskVo);
        }
        return R.error(StatusEnum.PARAM_INVALID);
    }


    //提交作业 图片、附件返回地址
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws Exception {
        //原始的文件名
        String originalFilename = file.getOriginalFilename();
        //新命名文件名称
        String url = AliOssUtil.uploadFile(originalFilename, file.getInputStream());
        if (StringUtils.isNullOrEmpty(url)) {
            return R.error(StatusEnum.PARAM_INVALID);
        }
        return R.success(url);
    }


    /**
     * 添加到redis
     * @param taskSave
     * @return
     */
    @PostMapping("/insertTaskRedis")
    public R insertTaskRedis(@RequestBody TaskSave taskSave) {
        //获取学生编号
        Integer studentId = taskSave.getStudentId();
        //判断操作是否成功
        boolean bool=false;
        //判断redis是否存在
        List<Object> taskList = redisTemplate.opsForList().range(studentId.toString(), 0, -1);
        //判断集合是否为空,为空则说明当前无键为studentId的集合
        if (ObjectUtils.isEmpty(taskList)) {
            //添加到redis
            redisTemplate.opsForList().rightPush(studentId.toString(), taskSave);
            bool=true;
        }else {
            //遍历取到的集合
            for (int i = 0; i < taskList.size(); i++) {
                //取到当前的集合元素
                TaskSave index = (TaskSave) redisTemplate.opsForList().index(studentId.toString(), i);
                //判断当前集合元素是否和传过来的元素相等
                if (index.getTaskId()==taskSave.getTaskId()){
                    //替换对象
                    redisTemplate.opsForList().set(studentId.toString(),i,taskSave);
                    bool=true;
                }else {
                    //添加对象
                    redisTemplate.opsForList().rightPush(studentId.toString(),taskSave);
                    bool=true;
                }
            }
        }
        //判断是否添加成功
        if (bool){
            return R.success("新增成功");
        }
        //判断是否添加成功
        return R.error(StatusEnum.PARAM_INVALID);
    }

    /**
     * 获取保存的redis集合
     * @param taskId
     * @return
     */
    @GetMapping("/getTaskRedis/{taskId}")
    public R<TaskSave> getTaskRedis(@PathVariable("taskId") Integer taskId){
        //获取redis集合
        List<Object> range = redisTemplate.opsForList().range("1", 0, -1);
        //遍历集合
        for (int i = 0; i < range.size(); i++) {
            //取集合元素
            TaskSave index = (TaskSave) redisTemplate.opsForList().index("1", i);
            if (index.getTaskId()==taskId){
                return R.success(index);
            }
        }
        return R.success(new TaskSave());
    }


//    根据学生编号查课程列表和学习进度
//    @GetMapping("/selectCourseListAndStudy")
//    public R<List<SelectCourseAndStudy>> selectCourseListAndStudy(@RequestHeader("token") String token){
//        //从网关获取当前访问的用户编号
//        Integer userid = Integer.parseInt(JwtUtils.getUserIdFromToken(token));
//        List<SelectCourseAndStudy> list = studentService.selectCourseAndStudy(userid);
//        return R.success(list);
//    }


    //根据课程编号查询该课程详细信息和学习进度
    @GetMapping("/selectCourseAndStudy/{courseId}")
    public R selectCourseAndStudy(@PathVariable Integer courseId) {
        return R.success(null);
    }

}
